package uploader

import (
	"errors"
	uuid "github.com/satori/go.uuid"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"path"
	"shop-common/library/loggerV2"
	"shop-common/utils/rand"
	"strconv"
)

/*
文件后缀名


文件大小验证
文件分隔符转化为当前系统的格式

判断文件的后缀名是否符合规则
*/

const (
	UploadMaxM           = 10
	UploadMaxBytes int64 = 1024 * 1024 * 1024 * UploadMaxM
)

func ValidUploadRequest(file multipart.File, header *multipart.FileHeader) (values *FileRequest, err error) {
	if header.Size > UploadMaxBytes {
		loggerV2.Error(err)
		return nil, errors.New("附件不能超过" + strconv.Itoa(UploadMaxM) + "M")
	}

	fileBytes, err := ioutil.ReadAll(file)
	if err != nil {
		loggerV2.Error(err)
		return nil, errors.New("附件不能读取")
	}

	//文件类型
	contentType := http.DetectContentType(fileBytes[:512])

	// 变更文件名
	newFileName := uuid.NewV4().String() + "-" + rand.GenerateRangeNumString(5) + path.Ext(header.Filename)

	return &FileRequest{
		RealName:    ReplaceFilename(header.Filename),
		NewFileName: newFileName,
		FileStream:  fileBytes,
		StreamSize:  len(fileBytes),
		FileType:    contentType,
	}, nil
}
